package com.jiuwu.spring.eshop;

import com.cksource.ckfinder.servlet.CKFinderServlet;
import com.jiuwu.spring.eshop.controller.UrlRequestInterceptor;
import com.jiuwu.spring.eshop.db.entity.Goods;
import com.jiuwu.spring.eshop.db.entity.SuperTypeWrapper;
import com.jiuwu.spring.eshop.db.entity.VGoods;
import com.jiuwu.spring.eshop.respository.GoodsRepository;
import com.jiuwu.spring.eshop.respository.VGoodsRepository;
import com.jiuwu.spring.eshop.respository.VTypeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;


@SpringBootApplication
@EnableJpaRepositories
@Slf4j

//@ServletComponentScan(basePackages = "com.jiuwu.spring.eshop.configuration")
public class EShopApplication extends SpringBootServletInitializer implements CommandLineRunner, ServletContextInitializer , WebMvcConfigurer {


//
//	@Autowired
//	private GoodsRepository goodsRepository;
//
//
//	@Autowired
//	private VTypeRepository vTypeRepository;
//
//
//	@Autowired
//	private VGoodsRepository vGoodsRepository;



	public static void main(String[] args) {
		SpringApplication.run(EShopApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		loadGoods();
	}

	private void loadGoods(){

//		List<Object[]> withType = vGoodsRepository.findGoodsWithType();
//		withType.forEach(items ->{
//			log.info("=======<>========");
//			for (Object item : items) {
//				log.info("item = {}",item);
//			}
//		});

//		Iterable<Goods> all = goodsRepository.findAll();
//		all.forEach(goods -> {
////			log.info("goods :{}",goods);
//
//		});
//
////		List<Object[]> types = vTypeRepository.findAllGroupBySuperId();
////		types.forEach(type -> {
////			log.info("type:{}",type);
////		});
//		List<SuperTypeWrapper> types = vTypeRepository.findAllGroupBySuperId();
//		types.forEach(type -> {
////			log.info("type:{},{}",type.getSuperId(),type.getSuperType());
//		});
//
//
////		List<VGoods> totalDesc = vGoodsRepository.findTop3BySoldTotalGreaterThanEqualOrderBySoldTotalDesc(1);
////
////		totalDesc.forEach( vgood ->{
//////			log.info("vgoods ->{}",vgood);
////		});

	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new UrlRequestInterceptor()).excludePathPatterns("*.js","*.gif","*.css").addPathPatterns("/**");
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {

		// Register the CKFinder's servlet.
		ServletRegistration.Dynamic dispatcher = servletContext.addServlet("ckfinder", new CKFinderServlet());
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/ckfinder/*");
		dispatcher.setInitParameter("scan-path", "com.jiuwu.spring.eshop.ckfinder");

		FilterRegistration.Dynamic filter = servletContext.addFilter("x-content-options", new Filter() {
			@Override
			public void init(FilterConfig filterConfig) {
			}

			@Override
			public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
				((HttpServletResponse) response).setHeader("X-Content-Type-Options", "nosniff");
				chain.doFilter(request, response);
			}

			@Override
			public void destroy() {
			}
		});

		filter.addMappingForUrlPatterns(null, false, "/images/*");

		String tempDirectory;

		try {
			tempDirectory = Files.createTempDirectory("ckfinder").toString();
		} catch (IOException e) {
			tempDirectory = null;
		}

		dispatcher.setMultipartConfig(new MultipartConfigElement(tempDirectory));
	}


	//ckfinder demo 路径
	// http://localhost:8080/ckfinder/static/samples/index.html
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// Configure the resource handler to serve files uploaded with CKFinder.
		String publicFilesDir = String.format("file:%s/images/", System.getProperty("user.dir"));

		registry.addResourceHandler("/images/**")
				.addResourceLocations(publicFilesDir);

//		registry.addResourceHandler("/**")
//				.addResourceLocations("/resources/static/").setCachePeriod(3600)
//				.resourceChain(true).addResolver(new PathResourceResolver());

	}


}
